from five import grok
from zope import schema
from zope.component.interfaces import IObjectEvent
from zope.component.interfaces import ObjectEvent
from zope.app.container.interfaces import IObjectAddedEvent
from zope.app.container.interfaces import IObjectModifiedEvent
from Products.ATContentTypes.interface.link import IATLink
from ownie.shorturl.interfaces import IShortURL
from zope.interface import Interface, implements, alsoProvides, providedBy, noLongerProvides
from Products.CMFCore.utils import getToolByName
from zope.annotation.interfaces import IAnnotations
from zope.event import notify
from collective.contentleadimage.extender import LeadImageExtender
from collective.contentleadimage.interfaces import ILeadImageable
from collective.contentleadimage.extender import LeadimageImageField
from collective.contentleadimage.config import IMAGE_FIELD_NAME
import ownie.shorturl
import os
import time

from zope.app.container.contained import ObjectAddedEvent, ObjectRemovedEvent, ObjectMovedEvent
from zope.lifecycleevent import ObjectModifiedEvent


class IAddShortURLEvent(IObjectEvent):
    """This is an event used to generate a short URL and rename
    the object, or set its id according to the short ID.
    """

class IShortURLPendingAnnotation(Interface):
    """Marker interface used to locate an object after it has been created.
    This object is provided on creation, and removed if existing on the modified event,
    in which case is triggers AddShortURL Event
    """

class IShortURLUnindexed(Interface):
    """Marker interface for later indexing of the object metadata.
    The metadata is short URL related annotations. These are:
     * Image
     * Keywords
     * Title
    There will be a Cron job looking for this marker interface.
    This interface will be changed to IShortURLExpectedIndex while
    the metadata is being fetched.
    """

class IBogusURL(Interface):
    """Marker interface for later indexing of the object metadata.
    The metadata is short URL related annotations. These are:
     * Image
     * Keywords
     * Title
    There will be a Cron job looking for this marker interface.
    This interface will be changed to IShortURLExpectedIndex while
    the metadata is being fetched.
    """

class IShortURLExpectedIndex(Interface):
    """This marker interface temporarily marks a object
    for which metadata is being fetched, previously marked by IShortURLUnindexed.
    Once the metadata is acquired, a second cron job will populate the metadata:
     * Image
     * Keywords
     * Title
    thereby removing this interface.
    """

#Interfaces that needs to be provided by new Links.
ifaces = (IShortURL, IShortURLPendingAnnotation, IShortURLUnindexed,)


class AddShortURLEvent(ObjectEvent):
    """This event is caused after a Link was created. It gets triggered
    on the ObjectModifiedEvent for objects providing the IShortURLPendingAnnotation.
    The goal of this event is to generate a short URL and rename the Object's id to the 
    short url.
    --object is the link and url the short url.
    """
    grok.implements(IAddShortURLEvent)
    
    def __init__(self, object, url, request):
        """object is the link and url the short url.
        """
        self.object = object
        self.url = url
        self.request = request

#@grok.subscribe(IATLink, IObjectAddedEvent)
def provideInterfaces(obj, event):
    """Provide ifaces to new Links.
    """
    if event.newParent.meta_type == "ATFolder":
        for iface in ifaces:
            if not iface.providedBy(obj):
                alsoProvides(obj, iface)
    notify(event)


#@grok.subscribe(IShortURLPendingAnnotation, IObjectModifiedEvent)
def triggerAnnotationsAndShortURL(obj, event, REQUEST=None):
    """After creation or IObjectAddedEvent, the IObjectModifiedEvent
    is called and looks for IShortURLPendingAnnotation marker interface.
    If found, default annotations are made.
    """
    return
    try:
        shorturl = getToolByName(obj, 'portal_shorturl')
        noLongerProvides(obj, IShortURLPendingAnnotation)
        shorturl = shorturl.seed(obj.UID())
        print 'Obj:', obj, shorturl, obj.getId()
        obj.aq_inner.aq_parent.manage_renameObject(obj.getId(), shorturl, REQUEST)
        notify(AddShortURLEvent(obj, shorturl))
        return obj
    except Exception, e:
        print e

@grok.subscribe(IShortURL, IAddShortURLEvent)
def annotateShortURL(obj, event):
    """Attach the default metadata and adds default values to the fields.
    """
    print 'annotating'
    annotations = IAnnotations(obj)
    annotations['ownie.shorturl.url'] = event.url
    annotations['ownie.shorturl.visits'] = 0
    try:
        annotations['ownie.shorturl.user-agent'] = [(time.gmtime(), event.request['HTTP_USER_AGENT'])]
        annotations['ownie.shorturl.session'] = [(time.gmtime(), event.request['SESSION'])]
        annotations['ownie.shorturl.remote-addr'] = [(time.gmtime(), event.request['REMOTE_ADDR'])]
        annotations['ownie.shorturl.lang'] = [(time.gmtime(), event.request['HTTP_ACCEPT_LANGUAGE'])]
        annotations['ownie.shorturl.cookie'] = [(time.gmtime(), event.request['HTTP_COOKIE'])]
    except Exception, e:
        print 'ANNOTATION', e
    
    #if ILeadImageable.providedBy(obj):
    #    print 'true...'
    #    leadImage = None
    #    for field in LeadImageExtender(obj).fields:
    #        if field.__class__ == LeadimageImageField:
    #            leadImage = field
    #    if leadImage:
    #        path = os.path.sep.join(ownie.shorturl.__file__.split(os.path.sep)[:-1] + ['static', 'pending.png'])
    #        data = open(path, 'rb').read()
    #        leadImage.set(obj, data)
    obj.reindexObject()


